package cn.edu.seig.textbook.service.impl;

import cn.edu.seig.textbook.domain.pojo.Permissions;
import cn.edu.seig.textbook.domain.pojo.Users;
import cn.edu.seig.textbook.mapper.UsersMapper;
import cn.edu.seig.textbook.repositiory.PermissionsRepositiory;
import cn.edu.seig.textbook.repositiory.UserRepositiory;
import cn.edu.seig.textbook.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author day
 * @since 2024-11-07
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    @Autowired
    private UsersMapper usersMapper;

    @Override
    public Users findByUserId(int userId) {
        return usersMapper.selectById(userId);
    }

    @Override
    public boolean addUsers(Users users) {
        return usersMapper.insertOrUpdate(users);
    }

    @Override
    public int deleteByUserId(Integer userId) {
        return usersMapper.deleteById(userId);
    }
    @Autowired
    private UserRepositiory userRepositiory;
    @Autowired
    private PermissionsRepositiory permissionsRepositiory;
    @Autowired
    private RedisTemplate redisTemplate;
    // 业务控制：使用唯一用户名查询用户信息
    public Users getUser(String username){
        Users user=null;
        Object o = redisTemplate.opsForValue().get("user_"+username);
        if(o!=null){
            user=(Users)o;
        }else {
            user = userRepositiory.findByUsername(username);
            if(user!=null){
                redisTemplate.opsForValue().set("user_"+username,user);
            }
        }

        return user;
    }
    // 业务控制：使用唯一用户名查询用户权限
    public List<Permissions> getUserAuthority(String username){
        List<Permissions> authorities=null;
        Object o = redisTemplate.opsForValue().get("authorities_"+username);
        if(o!=null){
            authorities=(List<Permissions>)o;
        }else {
            authorities=permissionsRepositiory.findPermissionsByUsername(username);
            if(authorities.size()>0){
                redisTemplate.opsForValue().set("authorities_"+username,authorities);
            }
        }
        return authorities;
    }
}
